package core.base;

import java.util.Calendar;
import java.util.Date;
import java.util.Set;
import java.util.TreeSet;

import core.util.StringUtil;

public class TimeServiceImpl implements TimeService {
	private static Set<Integer> quarterFirstMonths;

	static {
		quarterFirstMonths = new TreeSet<Integer>();
		quarterFirstMonths.add(Calendar.JANUARY);
		quarterFirstMonths.add(Calendar.APRIL);
		quarterFirstMonths.add(Calendar.JULY);
		quarterFirstMonths.add(Calendar.OCTOBER);
	}

	public long currentTimeMillis() {
		return System.currentTimeMillis();
	}

	public Date getNow() {
		return new java.util.Date();
	}

	public Calendar getNowCalendar() {
		return Calendar.getInstance();
	}

	public boolean isDailyTrigger(String triggerTime, java.util.Date lastTriggerTime, java.util.Date now1) {
		int hour = Integer.valueOf(triggerTime.substring(0, 2), 10);
		int min = Integer.valueOf(triggerTime.substring(2), 10);
		Calendar now = Calendar.getInstance();
		now.setTimeInMillis(now1.getTime());
		if (lastTriggerTime != null) {
			String today = StringUtil.format("yyyyMMdd", now.getTime());
			Calendar cal = getNowCalendar();
			cal.setTimeInMillis(lastTriggerTime.getTime());
			String lastDay = StringUtil.format("yyyyMMdd", cal.getTime());
			if (today.equals(lastDay)) {
				return false;
			}
		}

		Calendar cal = getNowCalendar();
		cal.setTimeInMillis(now.getTimeInMillis());
		cal.set(Calendar.HOUR_OF_DAY, hour);
		cal.set(Calendar.MINUTE, min);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);

		if (now.before(cal)) {
			return false;
		}

		return true;
	}

	public boolean isWeeklyFirstDay(Calendar cal) {
		return cal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY;
	}

	public boolean isMonthFirstDay(Calendar cal) {
		return cal.get(Calendar.DAY_OF_MONTH) == 1;
	}

	public boolean isQuarterFirstDay(Calendar cal) {
		return cal.get(Calendar.DAY_OF_MONTH) == 1 && quarterFirstMonths.contains(cal.get(Calendar.MONTH));
	}

	public boolean isYearFirstDay(Calendar cal) {
		return cal.get(Calendar.DAY_OF_YEAR) == 1;
	}

}
